import React, { useEffect, useState } from 'react';
import { Button, message, Row, Col } from 'antd';
import ProForm, {
    ProFormSelect,
    ProFormText,
    ProFormDatePicker,
    ProFormUploadButton,
} from '@ant-design/pro-form';
import styles from './index.scss';
import {
    fetchBookTypeList,
    modifyBook,
    batchModifyBook,
    fetchBookDetails,
} from '@/service/enrollBook';
import { BookType, EnrollBookState } from './interface';
import { UploadProps } from 'antd/lib/upload';
import useRerender from '@/hooks/useRerender';
import { uploadFile } from '@/service/personnelEntry';
import { history } from 'umi';
type NamePath = string | number | (string | number)[];
export default function Edit(props: any) {
    const bookid = props.match.params.id;
    const [form] = ProForm.useForm();
    const rerender = useRerender();
    const [bookTypeList, setbookTypeList] = useState<BookType[]>();
    const requestBookTypeList = async () => {
        const response = await fetchBookTypeList();
        if (response?.data) {
            setbookTypeList(response.data || []);
        }
    };
    function transformToFormData(values: any[]): any[] {
        return values.map((item: any) => {
            return {
                ...item,
                ...(item.img_url
                    ? {
                          img_url: [
                              { response: item.img_url, url: item.img_url },
                          ],
                      }
                    : {}),
            };
        });
    }
    const dataSourceRequest = async () => {
        let id = bookid;
        if (bookid.length > 1) {
            id = bookid.split(',');
        }
        const response = await fetchBookDetails(id);
        if (response?.code === 200) {
            let obj: any = {};
            let list = response.data as unknown as EnrollBookState[] | [];
            (Array.isArray(list) ? list : [list]).map((item) => {
                obj[item.id] = transformToFormData([item]).reduce(
                    (result: any, item: any, index: number) => {
                        result[index] = item;
                        return result;
                    },
                    {},
                )[0];
            });

            form.setFieldsValue({
                ...form.getFieldsValue(true),
                ...obj,
            });
        }
    };
    const [list, setlist] = useState<string[]>(bookid.split(','));
    const submitAdd = async (data: EnrollBookState) => {
        const res = await modifyBook(data);
        if (res?.code === 200) {
            message.success('提交成功');
            history.push('/enrollBook');
        } else {
            message.warning('提交失败');
        }
    };
    const submitBatchAdd = async (data: string) => {
        const res = await batchModifyBook({ bookInfo: data });
        if (res?.code === 200) {
            message.success('提交成功');
            history.push('/enrollBook');
        } else {
            message.warning('提交失败');
        }
    };
    useEffect(() => {
        requestBookTypeList();
        dataSourceRequest();
    }, []);
    const getOptions = () => {
        return bookTypeList?.map((item) => {
            return {
                value: item.id,
                label: item.cate_name,
            };
        });
    };
    const customRequest: UploadProps['customRequest'] = async (options) => {
        // console.log(options);
        const formdata = new FormData();
        formdata.append('field', 'book');
        formdata.append('book', options.file);
        const res = await uploadFile(formdata);
        if (res.code !== 200) {
            message.error(res.msg);
            return;
        }
        options.onSuccess?.(res.data.url);
        rerender();
    };
    function deepCopy<T extends unknown>(sourceData: T): T {
        if (Array.isArray(sourceData)) {
            return sourceData.map((item) => deepCopy(item)) as T;
        }
        const obj: T = {} as T;
        for (let key in sourceData) {
            if (
                typeof sourceData[key] === 'object' &&
                sourceData[key] !== null
            ) {
                obj[key] = deepCopy(sourceData[key]);
            } else {
                obj[key] = sourceData[key];
            }
        }
        return obj;
    }
    const validateAndGetFormatValue = (values: any) => {
        let arr: EnrollBookState[] = [];
        Object.keys(values).map((i) => {
            let obj = deepCopy(values[i]);
            obj.book_id = values[i].id;
            obj.img_url = values[i]?.img_url[0]?.response;
            delete obj.id;
            arr.push(obj);
        });
        if (arr.length < 1) {
            submitAdd(arr[0]);
        } else {
            submitBatchAdd(JSON.stringify(arr));
        }
    };
    return (
        <>
            <ProForm form={form} submitter={false}>
                {list.map((item) => {
                    return (
                        <div
                            key={item}
                            style={{
                                background: '#fff',
                                padding: '20px',
                                marginBottom: '20px',
                            }}
                        >
                            <ProForm.Group>
                                <ProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'rfid'].flat(Infinity)}
                                    label="RFID编号"
                                    placeholder="请输入RFID编号"
                                    disabled={true}
                                />
                                <ProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'isbn'].flat(Infinity)}
                                    label="ISBN编号"
                                    placeholder="请输入ISBN编号"
                                    disabled={true}
                                />
                                <ProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'book_name'].flat(Infinity)}
                                    label="书名"
                                    placeholder="请输入书名"
                                />
                                <ProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'author'].flat(Infinity)}
                                    label="作者"
                                    placeholder="请输入作者"
                                />
                            </ProForm.Group>
                            <ProForm.Group>
                                <ProFormDatePicker
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'publish_date'].flat(Infinity)}
                                    label="出版时间"
                                />
                                <ProFormText
                                    rules={[
                                        {
                                            required: true,
                                            message: '这是必填项',
                                        },
                                    ]}
                                    width="md"
                                    name={[item, 'publishing_house'].flat(
                                        Infinity,
                                    )}
                                    label="出版社"
                                    placeholder="请输入出版社"
                                />
                                <ProFormSelect
                                    options={getOptions()}
                                    width="sm"
                                    name={[item, 'cate_id'].flat(Infinity)}
                                    label="类别"
                                />
                            </ProForm.Group>
                            <ProFormUploadButton
                                fieldProps={{ customRequest }}
                                max={1}
                                accept="image/*"
                                title="上传图片"
                                listType="picture-card"
                                name={
                                    [item, 'img_url'].flat(
                                        Infinity,
                                    ) as NamePath & string
                                }
                                rules={[
                                    { required: true, message: '这是必填项' },
                                ]}
                                label="封面上传"
                            />
                            {/* <div style={{ textAlign: 'right' }}>
                                <Button
                                    onClick={() => {
                                        form.resetFields([item]);
                                        rerender();
                                    }}
                                >
                                    清空
                                </Button>
                                <Button
                                    style={{ marginLeft: '10px' }}
                                    onClick={() => {
                                        if (list.length > 1) {
                                            let arr = list.filter(
                                                (i) => i !== item,
                                            );
                                            setlist(arr);
                                        }
                                    }}
                                >
                                    删除
                                </Button>
                            </div> */}
                        </div>
                    );
                })}
            </ProForm>
            <Row justify="space-between" className={styles.bottomButton}>
                <Col></Col>
                <Col>
                    <Button onClick={() => history.push('/enrollBook')}>
                        取消
                    </Button>
                    <Button
                        style={{
                            border: '1px solid #1890ff',
                            marginLeft: '20px',
                            color: 'rgb(24, 144, 255)',
                        }}
                        onClick={() =>
                            validateAndGetFormatValue(form.getFieldsValue(true))
                        }
                    >
                        提交
                    </Button>
                </Col>
            </Row>
        </>
    );
}
